<template>

  <a-directory-tree
      multiple
      :tree-data="treeDataList"
      style="min-width: 120px"
      :load-data="onLoadData"
      v-model:selectedKeys="selectedKeys"
      :block-node="true"
  >

  </a-directory-tree>


</template>

<script lang="ts">
import type {TreeProps} from 'ant-design-vue';
import {defineComponent, ref} from 'vue';
import {EventsOn} from "../../wailsjs/runtime";
import {LoadTreeNodes, ReadFileContent} from "../../wailsjs/go/main/App";
import {main} from "../../wailsjs/go/models";
import { DataNode } from 'ant-design-vue/lib/tree';

export default defineComponent({
  setup() {
    const selectedKeys = ref<string[]>([]);
    const treeDataList = ref<TreeProps['treeData']>(<any>[]);
    const onLoadData: TreeProps['loadData'] = (treeNode: DataNode) => {
      return new Promise((resolve, reject) => {
        LoadTreeNodes(treeNode.key!.toString()).then((data: main.TreeData[]) => {
          if (data && treeNode.dataRef.children) {
            treeNode.dataRef.children.length = 0;
            treeNode.dataRef.children.push(...data.map((value) => {
              return {
                title: value.title,
                isLeaf: value.isLeaf,
                key: value.key,
                children: value.children
              }
            }));
            treeDataList.value = [...treeDataList.value!];
            resolve();
          } else {
            reject();
          }
        }).catch((e) => alert(e));
      });
    };
    return {
      selectedKeys,
      onLoadData,
      treeDataList
    };
  },
  data() {
    return {
      tw: '100%',
      th: '100%',
    }
  },
  computed: {
    treeHeight() {
      return document.documentElement.clientHeight + "px";
    },
    treeWidth() {
      return document.documentElement.clientWidth + "px";
    }
  },
  inject: ['eventBus'],
  mounted() {
    window.addEventListener('resize', () => {
      this.tw = '100%';
      this.th = '100%';
    });

    EventsOn("SelectedFolderEvent", (treeData) => {
      if (treeData) {
        this.treeDataList!.length = 0;
        this.treeDataList!.push(treeData);
      }
    })

  },
  watch: {
    treeHeight: {
      immediate: true,
      handler(newData) {
        this.th = '100%';
      }
    },
    treeWidth: {
      immediate: true,
      handler(newData) {
        this.tw = '100%';
      }
    },
    selectedKeys: {
      immediate: true,
      handler(newData) {
        if (newData && newData.length == 1) {
          let key = newData[0];
          ReadFileContent(key).then((fileContent:any) => {
            this.eventBus!.emit("ReadFileContent", fileContent);
          }).catch(e => alert(e));
        }
      }
    }

  }

});
</script>

<style scoped>
.ant-tree {
  height: 100%;
  width: 100%;
}
</style>